package com.pxmeta.verify.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.imageaudit.model.v20191230.ScanImageRequest;
import com.aliyuncs.imageaudit.model.v20191230.ScanImageResponse;
import com.aliyuncs.imageaudit.model.v20191230.ScanTextRequest;
import com.aliyuncs.imageaudit.model.v20191230.ScanTextResponse;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.enums.ContentAuditEnum;
import com.pxmeta.common.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
public class VerifyService {
    private final IAcsClient client;

    public String auditText(String content) throws ClientException {
//        return ContentAuditEnum.PASS.getSuggestion();
        if (StringUtils.isBlank(content)){
            return ContentAuditEnum.PASS.getSuggestion();
        }

        if (content.contains("色情")){
            return ContentAuditEnum.BLOCK.getSuggestion();
        }
        List<String> labels = new ArrayList<>();
//        labels.add("politics");
//        labels.add("abuse");
//        labels.add("terrorism");
        labels.add("porn");
        labels.add("flood");
        labels.add("contraband");
        labels.add("ad");
        List<ScanTextRequest.Labels> labelsList = Lists.newLinkedList();
        for (String labelStr : labels) {
            ScanTextRequest.Labels label = new ScanTextRequest.Labels();
            label.setLabel(labelStr);
            labelsList.add(label);
        }
        ScanTextRequest request = new ScanTextRequest();
        List<ScanTextRequest.Tasks> tasksList = new ArrayList<>();
        ScanTextRequest.Tasks task = new ScanTextRequest.Tasks();
        task.setContent(content);
        tasksList.add(task);
        request.setTaskss(tasksList);
        request.setLabelss(labelsList);
        ScanTextResponse resp = client.getAcsResponse(request);
        boolean needReview = Boolean.FALSE;
        List<ScanTextResponse.Data.Element> elements = resp.getData().getElements();
        for (ScanTextResponse.Data.Element element : elements) {
            for (ScanTextResponse.Data.Element.Result result : element.getResults()) {
                String suggestion = result.getSuggestion();
                if (ContentAuditEnum.BLOCK.getSuggestion().equals(suggestion)){
                    //审核不通过
                    return suggestion;
                }
                if (ContentAuditEnum.REVIEW.getSuggestion().equals(suggestion)){
                    //需要人工审核
                    needReview = Boolean.TRUE;
                }
            }
        }
        if (needReview){
            return ContentAuditEnum.REVIEW.getSuggestion();
        }
        return ContentAuditEnum.PASS.getSuggestion();
    }

    /**
     * 自动审核
     * @param text
     * @param imgList
     * @return
     */
    @SneakyThrows
    public Status audit(List<String> text, List<String> imgList){
        return Status.SUCCESS;
//        StringBuilder content = new StringBuilder();
//        for (String str : text) {
//            if (StringUtils.isBlank(str)){
//                continue;
//            }
//            content.append(str);
//        }
//        Status status = Status.SUCCESS;
//        //发布动态，进入自动审核流程
//        String auditTextResult = this.auditText(content.toString());
//        if (ContentAuditEnum.BLOCK.getSuggestion().equals(auditTextResult)){
//            //审核不通过
//            status = Status.FAIL;
//            throw new ServiceException("内容违规！");
//        }
//        if (ContentAuditEnum.REVIEW.getSuggestion().equals(auditTextResult)){
//            //审核中
//            status = Status.PENDING;
//        }
//        if (CollectionUtil.isNotEmpty(imgList)) {
//            String auditImgResult = this.auditImg(imgList);
//            if (ContentAuditEnum.BLOCK.getSuggestion().equals(auditImgResult)){
//                status = Status.FAIL;
//            }
//            if (!ContentAuditEnum.BLOCK.getSuggestion().equals(auditTextResult)
//                    && ContentAuditEnum.REVIEW.getSuggestion().equals(auditImgResult)){
//                //人工审核
//                status = Status.PENDING;
//            }
//        }
//
//        return status;
    }

    //图片审核
    public String auditImg(List<String> imgList) throws ClientException {
        return ContentAuditEnum.PASS.getSuggestion();
//        if (CollectionUtil.isEmpty(imgList)){
//            return ContentAuditEnum.PASS.getSuggestion();
//        }
//        ScanImageRequest req = new ScanImageRequest();
//        List<String> scenes = new ArrayList<String>();
//        scenes.add("porn");
////        scenes.add("terrorism");
////        scenes.add("ad");
////        scenes.add("live");
//        req.setScenes(scenes);
//        List<ScanImageRequest.Task> tasks = new ArrayList<>();
//        for (String img : imgList) {
//            if (StringUtils.isBlank(img)){
//                continue;
//            }
//            ScanImageRequest.Task task = new ScanImageRequest.Task();
//            task.setDataId(UUID.randomUUID().toString());
//            task.setImageURL(img);
//            tasks.add(task);
//        }
//        req.setTasks(tasks);
//        ScanImageResponse resp = client.getAcsResponse(req);
//        List<ScanImageResponse.Data.Result> results = resp.getData().getResults();
//        boolean needReview = Boolean.FALSE;
//        for (ScanImageResponse.Data.Result result : results) {
//            List<ScanImageResponse.Data.Result.SubResult> subResults = result.getSubResults();
//            for (ScanImageResponse.Data.Result.SubResult subResult : subResults) {
//                String suggestion = subResult.getSuggestion();
//                if (ContentAuditEnum.BLOCK.getSuggestion().equals(suggestion)){
//                    //审核不通过
//                    return suggestion;
//                }
//                if (ContentAuditEnum.REVIEW.getSuggestion().equals(suggestion)){
//                    //需要人工审核
//                    needReview = Boolean.TRUE;
//                }
//            }
//        }
//
//        if (needReview){
//            return ContentAuditEnum.REVIEW.getSuggestion();
//        }
//
//        return ContentAuditEnum.PASS.getSuggestion();
    }


    @SneakyThrows
    public String auditVideo(Long id, String videoUrl){
//        VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
//        videoAsyncScanRequest.setSysAcceptFormat(FormatType.JSON); // 指定API返回格式。
//        videoAsyncScanRequest.setSysMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
//
//        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
//        Map<String, Object> task = Maps.newLinkedHashMap();
//        task.put("dataId", id.toString());
//        task.put("url", videoUrl);
//        tasks.add(task);
//
//        /**
//         * 设置要检测的场景。计费是依据此处传递的场景计算。
//         * 视频默认1秒截取一帧，您可以自行控制截帧频率。收费按照视频的截帧数量以及每一帧的检测场景计算。
//         * 举例：1分钟的视频截帧60张，检测色情（对应场景参数porn）和暴恐涉政（对应场景参数terrorism）2个场景，收费按照60张色情+60张暴恐涉政进行计费。
//         */
//        JSONObject data = new JSONObject();
//        data.put("scenes", Collections.singletonList("porn"));
//        data.put("tasks", tasks);
//        data.put("callback", "https://api.pengxinmeta.com/api/audit/auditVideoHandler");
//        data.put("seed", "pengxinVideoAudit");
//        videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
//        HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
//
//        if (httpResponse.isSuccess()) {
//            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
//            System.out.println(JSON.toJSONString(scrResponse, true));
//            int requestCode = scrResponse.getIntValue("code");
//            // 每一个视频的检测结果。
//            JSONArray taskResults = scrResponse.getJSONArray("data");
//            if (200 == requestCode) {
//                for (Object taskResult : taskResults) {
//                    // 单个视频的处理结果。
//                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
//                    if (200 == taskCode) {
//                        // 保存taskId用于轮询结果。
//                        return ((JSONObject) taskResult).getString("taskId");
//                    } else {
//                        throw new ServiceException("视频审核失败：" + JSON.toJSONString(taskResult));
//                    }
//                }
//            } else {
//                throw new ServiceException("视频机审服务异常！错误码："+requestCode);
//            }
//        }else {
//            throw new ServiceException("视频机审服务请求失败！");
//        }
        return null;
    }




}
